<template>
  <div class="sidebar-container">
    <div class="sidebar-content">
      <!-- 固定头部 -->
      <div class="sidebar-header">
        <h2 class="sidebar-title font-display">
          <template v-if="isTextObject">
            <el-button
                type="text"
                @click="handleBackClick"
                class="back-button"
            >
              <i class="el-icon-arrow-left"></i>
              <span class="text-[18px] font-bold font-display">Back to Tools</span>
            </el-button>
          </template>
          <template v-else>
            Design Tools
          </template>
        </h2>

        <template v-if="!isTextObject">
          <div class="tab-buttons">
            <el-button
                v-for="tab in tabs"
                :key="tab.id"
                :class="{ 'active-tab': activeTab === tab.id }"
                @click="activeTab = tab.id"
                size="medium"
            >
              <i :class="tab.icon"></i>
              <span>{{ tab.label }}</span>
            </el-button>
          </div>

          <div class="tab-content">
            <!-- 设计选项卡 -->
            <div v-if="activeTab === 'design'" class="design-tab">
              <div class="design-selector-card">
                <div class="design-header">
                  <h3>Select Design</h3>
                  <div class="design-price">
                    ￥{{ selectedDesignPrice }}
                  </div>
                </div>
                <design-selector :product-type="selectedProductType"></design-selector>
              </div>
            </div>

            <!-- 颜色选项卡 -->
            <div v-if="activeTab === 'color'">
              <color-palette></color-palette>
            </div>

            <!-- 文本选项卡 -->
            <div v-if="activeTab === 'text'">
              <el-button
                  @click="onAddText"
                  class="add-button"
              >
                <i class="el-icon-document"></i>
                <span>Add Text</span>
                <i class="el-icon-arrow-right"></i>
              </el-button>
            </div>

            <!-- 标志选项卡 -->
            <div v-if="activeTab === 'logo'">
              <el-button
                  @click="showImageUpload = true"
                  class="add-button"
              >
                <i class="el-icon-picture"></i>
                <span>Add Image</span>
                <i class="el-icon-arrow-right"></i>
              </el-button>
            </div>
          </div>
        </template>
      </div>

      <!-- 文本属性 -->
      <div v-if="isTextObject && selectedObject" class="text-properties">
        <h3>Text Properties</h3>
        <text-controls
            :current-text="selectedObjectText"
            :current-font="selectedObjectFont"
            :current-color="selectedObjectColor"
            :current-outline-width="selectedObjectOutlineWidth"
            :current-outline-color="selectedObjectOutlineColor"
            @text-change="handleTextChange"
            @font-change="handleFontChange"
            @color-change="handleColorChange"
            @outline-change="handleOutlineChange"
        ></text-controls>
      </div>

      <!-- 装饰列表 -->
      <div v-if="!isTextObject" class="decorations-list">
        <h3>Decorations</h3>
        <decorations-list
            :decorations="decorationsList"
            @select="onSelectDecoration"
            @delete="onDeleteDecoration"
            :selected-id="selectedObjectId"
        ></decorations-list>
      </div>

      <!-- 添加到购物车 -->
      <div class="add-to-cart">
        <div class="price-display">
          <span>Price per item:</span>
          <span class="price">￥{{ selectedDesignPrice }}</span>
        </div>
        <el-button
            @click="handleSaveDesign"
            :disabled="hasSelection"
            :class="{ 'disabled-button': hasSelection }"
            class="w-full"
            type="primary"
        >
          {{ hasSelection ? "Deselect to Add to Cart" : "Add to Cart" }}
        </el-button>
      </div>
    </div>

    <!-- 图片上传对话框 -->
    <el-dialog
        title="Upload Image"
        :visible.sync="showImageUpload"
        width="570px"
    >
      <image-upload
          :key="showImageUpload"
          @close="showImageUpload = false"
          @image-select="handleImageSelect"
      ></image-upload>
    </el-dialog>

    <!-- 模型选择对话框 -->
<!--    <el-dialog-->
<!--        title="选择模型"-->
<!--        :visible.sync="showModelSelector"-->
<!--        width="80%"-->
<!--    >-->
<!--      <model-selector @close="showModelSelector = false"></model-selector>-->
<!--    </el-dialog>-->
  </div>
</template>

<script>
import { mapState, mapGetters } from 'vuex';
import TextControls from './TextControls.vue';
import ImageUpload from './ImageUpload.vue';
import DesignSelector from './DesignSelector.vue';
import ColorPalette from './ColorPalette.vue';
import DecorationsList from './DecorationsList.vue';
// import ModelSelector from './ModelSelector.vue';

export default {
  name: 'SidebarComp',
  components: {
    TextControls,
    ImageUpload,
    DesignSelector,
    ColorPalette,
    DecorationsList,
    // ModelSelector
  },
  props: {
    currentView: {
      type: String,
      default: '3D'
    },
    selectedObject: {
      type: Object,
      default: null
    },
    fabricCanvas: {
      type: Object,
      default: null
    },
    hasSelection: {
      type: Boolean,
      default: false
    },
    isPlacingImage: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      showImageUpload: false,
      showModelSelector: false,
      view: this.currentView,
      quantity: 1,
      activeTab: 'design',
      tabs: [
        { id: 'design', label: 'Design', icon: 'el-icon-s-data' },
        { id: 'color', label: 'Color', icon: 'el-icon-brush' },
        { id: 'text', label: 'Text', icon: 'el-icon-document' },
        { id: 'logo', label: 'Logo', icon: 'el-icon-picture' }
      ]
    };
  },
  computed: {
    ...mapState({
      pathColors: state => state.colors.pathColors,
      currentSaveId: state => state.cart.currentSaveId,
      decorations: state => state.decorations.items,
      selectedProductType: state => state.designs.selectedProductType
    }),
    ...mapGetters({
      selectedDesign: 'designs/selectedDesign'
    }),
    selectedModel() {
      return this.$store.state.models.models.find(
          m => m.id === this.selectedDesign?.modelId
      );
    },
    isTextObject() {
      return this.selectedObject?.type === 'i-text';
    },
    selectedObjectId() {
      return this.selectedObject?.id;
    },
    selectedObjectText() {
      return this.selectedObject?.text || '';
    },
    selectedObjectFont() {
      return this.selectedObject?.fontFamily || 'Arial';
    },
    selectedObjectColor() {
      return this.selectedObject?.fill || '#000000';
    },
    selectedObjectOutlineWidth() {
      return this.selectedObject?.strokeWidth || 0;
    },
    selectedObjectOutlineColor() {
      return this.selectedObject?.stroke || '#000000';
    },
    selectedDesignPrice() {
      return this.selectedDesign?.price?.toFixed(2) || '0.00';
    },
    decorationsList() {
      return this.decorations.map(d => ({
        id: d.id,
        type: d.type,
        preview: d.type === 'text'
            ? d.properties.text || 'Text'
            : 'Image'
      }));
    }
  },
  methods: {
    onAddText() {
      this.$emit('add-text');
    },
    onSelectDecoration(id) {
      this.$emit('select-decoration', id);
    },
    onDeleteDecoration(id) {
      this.$emit('delete-decoration', id);
    },
    handleBackClick() {
      this.$emit('update-selected-object', null)
    },
    handleImageSelect(file) {
      this.$emit('add-image', file);
      this.showImageUpload = false;
    },
    handleTextChange(text) {
      this.$emit('update-selected-object', { text })
    },
    handleFontChange(fontFamily) {
      this.$emit('update-selected-object', { fontFamily })
    },
    handleColorChange(fill) {
      this.$emit('update-selected-object', { fill })
    },
    handleOutlineChange(width, color) {
      this.$emit('update-selected-object', {
        strokeWidth: width,
        stroke: color
      })
    },
    async handleSaveDesign() {
      if (!this.selectedDesign || !this.fabricCanvas) {
        return;
      }

      try {
        // 存储当前视图状态
        const currentView = this.view;

        // 强制3D视图并截图
        this.view = '3D';
        await new Promise(resolve => setTimeout(resolve, 100));

        const preview = await this.$emit('take-screenshot') || '';

        // 恢复之前的视图
        this.view = currentView;

        const objects = this.fabricCanvas.getObjects();
        const updatedDecorations = objects
            .filter(obj => !obj.data?.isBackground && obj.id)
            .map(obj => {
              const baseProperties = {
                left: obj.left || 0,
                top: obj.top || 0,
                scaleX: obj.scaleX || 1,
                scaleY: obj.scaleY || 1,
                angle: obj.angle || 0,
                opacity: obj.opacity || 1
              };

              if (obj.type === 'i-text') {
                return {
                  id: obj.id,
                  type: 'text',
                  properties: {
                    ...baseProperties,
                    text: obj.text || '',
                    fontFamily: obj.fontFamily || 'Arial',
                    fill: obj.fill || '#000000',
                    strokeWidth: obj.strokeWidth || 0,
                    stroke: obj.stroke || '#000000'
                  }
                };
              } else {
                return {
                  id: obj.id,
                  type: 'image',
                  properties: {
                    ...baseProperties,
                    src: obj.getSrc()
                  }
                };
              }
            });

        const vectorData = JSON.stringify(this.fabricCanvas.toJSON(['id', 'data', 'opacity']));

        const currentPathColors = Array.isArray(this.pathColors) ? this.pathColors : [];

        const newDesign = {
          id: this.currentSaveId || Date.now().toString(),
          saveId: this.currentSaveId,
          timestamp: Date.now(),
          design: this.selectedDesign,
          modelPath: this.selectedModel?.path,
          pathColors: currentPathColors,
          decorations: updatedDecorations,
          preview,
          vectorData,
          quantity: this.quantity,
        };

        this.$store.dispatch('cart/addToCart', newDesign);
        this.$router.push('/cart');
      } catch (error) {
        console.error('保存设计失败:', error);
        this.$message.error('保存设计失败');
      }
    }
  }
};
</script>

<style scoped>
.sidebar-container {
  width: 390px;
  height: auto;
  background: white;
  border-top: 1px solid #e6e6e6;
  display: flex;
  flex-direction: column;
}

.sidebar-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  padding: 16px;
}

.sidebar-header {
  padding-bottom: 16px;
  border-bottom: 1px solid #e6e6e6;
}

.sidebar-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 16px;
  color: #333;
}

.back-button {
  display: flex;
  align-items: center;
  color: #666;
}

.back-button:hover {
  color: #333;
}

.tab-buttons {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 4px;
  background: #f5f5f5;
  padding: 4px;
  border-radius: 4px;
  margin-bottom: 16px;
}

.tab-buttons .el-button {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 8px 4px;
  width: 100%;
}

.tab-buttons .el-button span {
  font-size: 12px;
  margin-top: 4px;
}

.active-tab {
  background: white !important;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  color: #409EFF !important;
}

.design-tab {
  margin-top: 16px;
}

.design-selector-card {
  background: white;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 16px;
}

.design-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.design-header h3 {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.design-price {
  font-size: 14px;
  color: #666;
}

.add-button {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: white;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
}

.add-button:hover {
  background: #f5f5f5;
}

.text-properties {
  margin-top: 16px;
}

.text-properties h3 {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 16px;
  color: #333;
}

.decorations-list {
  margin-top: 16px;
}

.decorations-list h3 {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 16px;
  color: #333;
}

.add-to-cart {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #e6e6e6;
}

.price-display {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  background: #f5f5f5;
  border-radius: 4px;
  margin-bottom: 16px;
}

.price-display .price {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.disabled-button {
  cursor: not-allowed;
  opacity: 0.7;
}
</style>